package com.abc.rule.aviator;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorLong;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class DayBetweenNotYearFunction extends AbstractFunction {

   @Override
   public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {

      try {
         Object left = FunctionUtils.getJavaObject(arg1, env);

         if ("-1".equals(left)) {
            return new AviatorLong(-9999);
         }
         SimpleDateFormat format = new SimpleDateFormat("MM");
         SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM");

         String curStr = format.format(new Date());

         String opeDate = format.format(format2.parse(left.toString()));

         int monBetween = Integer.parseInt(opeDate) - Integer.parseInt(curStr);

         return new AviatorLong(monBetween);
      }
      catch (Exception e) {
         return new AviatorLong(-9999);
      }
   }

   @Override
   public String getName() {
      return "dayBetweenNotYear";
   }

}